// 在给定一个一组数中查找最大的数
// a0: usize数组的指针
// a1: usize数组的大小
.align 3
.section .text
.global homework_5_1
.type homework_5_1, %function
homework_5_1:
    addi sp, sp, -16
    sd ra, 8(sp)

    mv t0, a0
    mv t1, a1
    addi t1, t1, -1
    ld t3, (t0)
    beqz t1, ret
    loop:
        addi t0, t0, 8
        ld t4, (t0)
        bgtu t4, t3, great
        addi t1, t1, -1
        bnez t1, loop
        j ret
    great:
        mv t3, t4
        addi t1, t1, -1
        bnez t1, loop

    ret:
    mv a0, t3
    ld ra, 8(sp)
    addi sp, sp, 16
    ret



// 5-2 汇编语言实现一个汇编函数，用于比较两个数的大小，并返回较大的值
.section .text
.global homework_5_2
.type homework_5_2, %function
homework_5_2:
    addi sp, sp, -16
    sd ra, 8(sp)
    bgeu a0, a1, homework_5_2_return    // a >= b
    mv a0, a1                           // a<b交换
    homework_5_2_return:
    ld ra, 8(sp)                        // 恢复
    addi sp, sp, 16                     // 通过a0返回了值
    ret

// 5-3从汇编调用c函数，比较大小
.section .data
.align 3
.local data1
data1:
    .quad 670

.local
data2:
    .quad 30

.section .text
.align 3
.global homework_5_3_call
.type homework_5_3_call, %function
homework_5_3_call:
    addi sp, sp, -16
    sd ra, 8(sp)
    ld a0, data1
    ld a1, data2
    call homework_5_3       // 返回值在a0中
    call example5_print
    ld ra, 8(sp)
    addi sp, sp, 16
    ret

// 5-4 定义一个表
.section .data
.align 3
.global homework_5_4_address_table
.type homework_5_4_address_table, %object
homework_5_4_address_table:
    .quad 0x800800
    .quad 0x800860
    .quad 0x800880

.global homework_5_4_func_table
.type homework_5_4_func_table, %object
homework_5_4_func_table:
    .string "func_a"
    .string "func_b"
    .string "func_c"

.global homework_5_4_table_size
.type homework_5_4_table_size, %object
homework_5_4_table_size:
    .quad 3

// 5-5汇编宏的使用
.macro op_func op, a, b
    mv a0, \a
    mv a1, \b
    call homework_5_5_\()\op
.endm

.align 3
.section .text
.local homework_5_5_1
.type homework_5_5_1, %function
homework_5_5_1:
    addi sp, sp, -16
    sd ra, 8(sp)
    add a0, a0, a1
    ld ra, 8(sp)
    addi sp, sp, 16
    ret

.align 3
.section .text
.local homework_5_5_2
.type homework_5_5_2, %function
homework_5_5_2:
    addi sp, sp, -16
    sd ra, 8(sp)
    addi a0, a0, 5
    add a0, a0, a1
    ld ra, 8(sp)
    addi sp, sp, 16
    ret

.global homework_5_5_test1
.type homework_5_5_test1, %function
homework_5_5_test1:
    addi sp, sp, -16
    sd ra, 8(sp)
    mv t0, a0
    mv t1, a1
    op_func 1, t0, t1
    ld ra, 8(sp)
    addi sp, sp, 16
    ret

.global homework_5_5_test2
.type homework_5_5_test2, %function
homework_5_5_test2:
    addi sp, sp, -16
    sd ra, 8(sp)
    mv t0, a0
    mv t1, a1
    op_func 2, t0, t1
    ld ra, 8(sp)
    addi sp, sp, 16
    ret